//
//  WelcomeViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "WelcomeViewController.h"
#import "AppDelegate.h"
#import "Deck.h"
#import <QuartzCore/QuartzCore.h>
#import "ImageCache.h"
#import "CheckCardUtils.h"
@interface WelcomeViewController ()

@end
#define LOADING_BAR_WIDTH 71.0
#define LOADING_BAR_HEIGHT 4.0
@implementation WelcomeViewController
-(IBAction)showHelpPopup:(id)sender
{
     [[AppDelegate sharedController] showHelpPopup];
}
-(IBAction)showLoginScreen:(id)sender
{
    [[AppDelegate sharedController] showSignInScreen];
}

-(IBAction)showSignUpScreen:(id)sender
{
     [[AppDelegate sharedController] showSignUpScreen];
}

-(IBAction)showMainScreen:(id)sender
{
     [[AppDelegate sharedController] showMainScreen];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
UIImageView *cardImageView;
- (void)viewDidLoad
{

    // Do any additional setup after loading the view from its nib.
   /* Deck *deck = [AppDelegate sharedController].deck;
    UIImage *backImage = deck.backImage;
    
    CGSize cardSize = backImage.size;    
    cardSize.width = ceilf(cardSize.width);
    cardSize.height = ceilf(cardSize.height);
    
    
        CGRect frame = CGRectMake(0, 0, cardSize.width, cardSize.height);
        cardImageView = [[[UIImageView alloc] initWithFrame:frame] autorelease];
    Card *card = [deck randomCard];
    CardItem *cardItem = [CardItem cardItemWithCard:card closed:NO];
        if (nil != cardItem.card)
        {
            [cardImageView setImage:cardItem.card.image];
            [cardImageView setHighlightedImage:backImage];
            cardImageView.highlighted = YES;
        }
        else
        {
            [cardImageView setImage:backImage];
        }
        
        [self.view addSubview:cardImageView];
    */
    /*CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:cardImageView cache:YES];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.50f];
    [UIView setAnimationRepeatCount:100];
    [UIView commitAnimations];*/



/*CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 1.0, 0);
CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];

rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 0.25f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1;
rotationAnimation.delegate = self;
[cardImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];*/
   
    /*CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    //CGPathAddQuadCurveToPoint(path, NULL, 10, 10, 30, 200);
    CGPathAddCurveToPoint(path, NULL, 200, 10, 100, 200, 100, 250);
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.path = path;
    pathAnimation.duration = 0.5;
    pathAnimation.repeatCount = 1;
    pathAnimation.rotationMode = kCAAnimationRotateAutoReverse;
    
    [cardImageView.layer addAnimation:pathAnimation forKey:nil];
    */
   // [self deal];

    splash = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height)];
    [splash setImage:[ImageCache loadImage:@"Default.png"]];
    [self.view addSubview:splash];
    
    [splash release];
    
    NSMutableArray* loadingArray = [[NSMutableArray alloc] initWithCapacity:1];
    
    for (int i = 0; i < 17; i++)
    {
        [loadingArray addObject:[ImageCache loadImage:[NSString stringWithFormat:@"loadingbar%d.png", i+1]]];
    }
    
    UIImageView* loadingBar = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - LOADING_BAR_WIDTH) / 2.0f, 320.0f, LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT)];
    loadingBar.animationImages = loadingArray;
    loadingBar.animationDuration = 2.0f;
    loadingBar.animationRepeatCount = 1;
    [splash addSubview:loadingBar];
    
    [loadingBar startAnimating];
    [loadingBar release];
    [loadingArray release];
    
    [self performSelector:@selector(removeSplash) withObject:nil afterDelay:2.5f];
    [super viewDidLoad];
    
    // Check card ......
    /*NSMutableArray* arrCards = [NSMutableArray array];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRankAce suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank2 suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRankJack suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank3 suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank5 suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank7 suit:kCardSuitHearts]];
    [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank10 suit:kCardSuitHearts]];
    BestCardsInfo* result1 = [CheckCardUtils checkBestCard:arrCards];
    [CheckCardUtils debugCards:result1.bestCards tips:[result1 debugBestHand]];
    */
    /*NSArray * result = [CheckCardUtils checkFlush:arrCards];
    [CheckCardUtils debugCards:result tips:@"Flush"];
    NSArray * result2 = [CheckCardUtils checkRoyalFlush:result];
    [CheckCardUtils debugCards:result2 tips:@"RoyalFlush"];
    NSArray * result3 = [CheckCardUtils checkStraightFlush:result];
    [CheckCardUtils debugCards:result3 tips:@"StraightFlush"];
    NSArray * result4 = [CheckCardUtils checkStraight:arrCards];
    [CheckCardUtils debugCards:result4 tips:@"Straight"];*/
    
    //NSMutableArray* arrCards = [NSMutableArray array];
    /*arrCards = [NSMutableArray array];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRankAce suit:kCardSuitHearts]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank3 suit:kCardSuitHearts]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRankAce suit:kCardSuitDiamonds]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank4 suit:kCardSuitSpades]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRankAce suit:kCardSuitClubs]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank4 suit:kCardSuitHearts]];
     [arrCards addObject:[[[AppDelegate sharedController] deck] cardWithRank:kCardRank7 suit:kCardSuitSpades]];
    
    BestCardsInfo* result2 = [CheckCardUtils checkBestCard:arrCards];
    [CheckCardUtils debugCards:result2.bestCards tips:[result2 debugBestHand]];
    */
    /*StatisticCards * statCards = [[StatisticCards alloc] init];
    [statCards parseCards:arrCards];
    NSArray * result5 = [CheckCardUtils checkFourOfAKind:statCards];
    [CheckCardUtils debugCards:result5 tips:@"FourOfAKind"];
    NSArray * result6 = [CheckCardUtils checkFullHouse:statCards];
    [CheckCardUtils debugCards:result6 tips:@"FullHouse"];
    NSArray * result7 = [CheckCardUtils checkThreeOfAKind:statCards];
    [CheckCardUtils debugCards:result7 tips:@"ThreeOfAKind"];
    NSArray * result8 = [CheckCardUtils checkTwoPair:statCards];
    [CheckCardUtils debugCards:result8 tips:@"TwoPair"];
    NSArray * result9 = [CheckCardUtils checkPair:statCards];
    [CheckCardUtils debugCards:result9 tips:@"Pair"];*/
    
   /*ResultCompareCards rCompare = [result1 compareBestCard:result2];
   if(rCompare == rCompareWin)
   {
       NSLog(@"Result 1 Win");
   }
    else  if(rCompare == rCompareLose)
    {
        NSLog(@"Result 1 Close");
    }
    else 
    {
        NSLog(@"Equal");
    }*/

}
- (void)removeSplash
{
    if (splash)
    {
        [splash removeFromSuperview];
        splash = nil;
    }
}

- (void)deal {
    // Of course, you'd replace these NSString objects with actual card objects...
    NSArray *array = [NSArray arrayWithObjects:@"pCard", @"dCard", @"pCard", @"dCard",@"tCard", @"tCard",@"tCard",@"tCard",@"tCard",nil];
    [self performSelectorOnMainThread:@selector(animateDealWithArray:) withObject:array waitUntilDone:YES];
}
- (void)animateDealWithArray:(NSArray *)array {
    // constants that won't change call to call
    static CGFloat duration = 0.5;
    static CGSize  cardSize = {75,  110};
    static CGPoint playerTo = {100, 0};
    static CGPoint dealerTo = {100, 400};
    static CGPoint turnTo = {50, 180};
    // Do any additional setup after loading the view from its nib.
    Deck *deck = [AppDelegate sharedController].deck;
    UIImage *backImage = deck.backImage;
    
    CGSize cSize = backImage.size;    
    cSize.width = ceilf(cSize.width);
    cSize.height = ceilf(cSize.height);
    cardSize = cSize;
    // Seems like you want the card to start at the top of the "deck" whether it's a player card or not
    UIImageView *card = [[UIImageView alloc] initWithFrame:CGRectMake(320, 180, cSize.width, cSize.height)];
    // Figure out if the first object (the one we're currently using) is a player or dealer card
    NSString* str = [array objectAtIndex:0] ;
    if (str == @"pCard") {
        // Player card, so show the "face"
       [card setImage:[UIImage imageNamed:@"Deck1_card_back.png"]];
           [self.view addSubview:card];
        [UIView animateWithDuration:duration
                         animations:^{
                             [card setFrame:CGRectMake(playerTo.x, playerTo.y, cardSize.width, cardSize.height)];
                         }
                         completion:^(BOOL finished) {
                             playerTo.x += cardSize.width + 3;
                             [self dealNext:array];
                             
                         }
         ];
    } 
    
    else if (str == @"dCard") 
    {
        // Dealer card, so show the back
        [card setImage:[UIImage imageNamed:@"row3__0015_0111_2.png"]];
        [self.view addSubview:card];
        [UIView animateWithDuration:duration
                         animations:^{
                             [card setFrame:CGRectMake(dealerTo.x, dealerTo.y, cardSize.width, cardSize.height)];
                         }
                         completion:^(BOOL finished) {
                             dealerTo.x += cardSize.width +3;
                             [self dealNext:array];
                              
                         }
         ];
    }
    
    else {
        // Dealer card, so show the back
        [card setImage:[UIImage imageNamed:@"row3__0015_0111_2.png"]];
        [self.view addSubview:card];
        [UIView animateWithDuration:duration
                         animations:^{
                             [card setFrame:CGRectMake(turnTo.x, turnTo.y, cardSize.width, cardSize.height)];
                         }
                         completion:^(BOOL finished) {
                              turnTo.x += cardSize.width +3;
                             [self dealNext:array];
                            
                         }
         ];

    }
}
- (void)dealNext:(NSArray *)array {
    int count = [array count];
    if (count > 1) {
        NSArray *newArray = [array subarrayWithRange:NSMakeRange(1, count - 1)];
        [self animateDealWithArray:newArray];
    }
}
-(void) animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
      cardImageView.highlighted = NO;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
